package com.quick.proxy.server;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.*;
import com.quick.proxy.core.utils.ByteUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * Description: 代理消息转发：将客户端代理的消息转发给访问者
 * Author: 吃素不吃肉
 * Date: 2023/7/3
 *
 * @author 吃素不吃肉
 */
@Match(CmdTypeConstants.FORWARD)
@Component
@Slf4j
public class ProxyMessageForwardHandler implements ProxyMessageHandler {
    /**
     * 接收的数据帧包
     *
     * @param ctx          上下文
     * @param proxyMessage 帧报文
     */
    @Override
    public void cmdResponse(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
        ForwardMessage forwardMessage = JSONUtil.toBean(ByteUtils.hexToString(proxyMessage.getData()), ForwardMessage.class);
        if (StrUtil.isEmpty(forwardMessage.getVisitorId())) {
            log.warn("visitorId is empty ");
            return;
        }
        //获取访问者通道
        Map<String, VisitorChannel> visitorIdChannel = ctx.channel().attr(ServerChannelAttribute.VISITOR_ID_CHANNEL).get();
        if (CollectionUtils.isEmpty(visitorIdChannel)) {
            log.warn("visitorId[{}]visitorIdChannel is null ", forwardMessage.getVisitorId());
            return;
        }
        VisitorChannel visitorChannel = visitorIdChannel.get(forwardMessage.getVisitorId());
        visitorChannel.getVisitorChannel().writeAndFlush(forwardMessage.getBytes());
        log.debug("visitorId[{}]Receive proxy messages:{}", forwardMessage.getVisitorId(), ByteUtils.bytesToHex(forwardMessage.getBytes()));
    }
}
